<?php

// no direct access
defined('_JEXEC') or die;

$session_vipcard =& JFactory::getSession();
$session_vipcard_id =  $session_vipcard->getId();

if($this->params['save'] == false && !empty($this->items)):

$summary = array();
$summary['point'] = 0;
$summary['cash'] = 0;
$product_out = '';

$page_heading = JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT');
$title = JText::_('WMCVIP_TITLE_PREFIX').$page_heading.JText::_('WMCVIP_TITLE_SUFIX');
$document = &JFactory::getDocument();
$document->setTitle($title) ; 

foreach($this->items as $id => $item){
    $images = '';
    if($item->img != '')
        if($item->cash != 0)
            $images = '<img title="'.urldecode($item->name).'" id="item_'.$item->id.'_2_img" class="thumb-img" alt="'.$item->name.'" title="'.$item->name.'" src="'.$item->img.'" />';
        else 
            $images = '<img title="'.urldecode($item->name).'" id="item_'.$item->id.'_img" class="thumb-img" alt="'.$item->name.'" title="'.$item->name.'" src="'.$item->img.'" />';
    else
        $images = '';

	if($item->cash != 0){
		
		$product_out .= '
            <div style="display:table-cell;vertical-align:middle;" class="sp1 item_'.$item->id.'_2_parent item_'.$item->id.'_'.$item->type.' ">
                 
				<span class="column01">'.$images.'</span>
                <span class="column02">
                    <input rel="'.$item->type.'" id="item_'.$item->id.'_2" readonly type="text"  class="spin2" name="item_'.$item->id.'_id_2_qty" value="'.$item->qty.'" />
                </span>
                <span class="column03"><span class="point_item_'.$item->id.'" >'.number_format($item->point * $item->qty + $item->pointx*$item->qty,0,',',',').'</span> '.JText::_('WRD_PROMOTION_POINTS');
		
		$product_out .= '<br> + <span class="cash_item_'.$item->id.'">'.number_format($item->cash*$item->qty,0,',',',')."</span>";
		$product_out .= '<input style="display:none" checked="checked" class="way_check" type="radio" name="item_'.$item->id.'_2_type" id="item_'.$item->id.'_id_2" value="2" />';
		$product_out .= '<input type="hidden" id="item_'.$item->id.'_id_2_point" value="'.$item->point.'" />';
        $product_out .= '<input type="hidden" id="item_'.$item->id.'_id_2_pointx" value="'.$item->pointx.'" />';
        $product_out .= '<input type="hidden" id="item_'.$item->id.'_id_2_cash" value="'.$item->cash.'" />';
		$product_out .= '<input type="hidden" id="item_'.$item->id.'_remain" value="'.$item->remain.'" />';
		$product_out .= '<input type="hidden" id="item_'.$item->id.'_qtyTotal" value="'.$item->qtyTotal.'" />';
		$product_out .= '<input type="hidden" id="item_'.$item->id.'_'.$item->type.'_cur" value="'.$item->qty.'" />';
	}
	else{
		
		$product_out .= '
            <div style="display:table-cell;vertical-align:middle;" class="sp1 item_'.$item->id.'_1_parent item_'.$item->id.'_'.$item->type.' ">
                
				<span class="column01">'.$images.'</span>
                <span class="column02">
                    <input rel="'.$item->type.'" id="item_'.$item->id.'" readonly type="text" class="spin2" name="item_'.$item->id.'_id_qty" value="'.$item->qty.'" />
                </span>
                <span class="column03"><span class="point_item_'.$item->id.'" >'.number_format($item->point * $item->qty + $item->pointx*$item->qty,0,',',',').'</span> '.JText::_('WRD_PROMOTION_POINTS');
		
		$product_out .= '<input style="display:none" checked="checked" class="way_check" type="radio" name="item_'.$item->id.'_type" id="item_'.$item->id.'_id" value="1" />';
		$product_out .= '<input type="hidden" id="item_'.$item->id.'_id_point" value="'.$item->point.'" />';
        $product_out .= '<input type="hidden" id="item_'.$item->id.'_id_pointx" value="'.$item->pointx.'" />';
        $product_out .= '<input type="hidden" id="item_'.$item->id.'_id_cash" value="'.$item->cash.'" />';
		$product_out .= '<input type="hidden" id="item_'.$item->id.'_remain" value="'.$item->remain.'" />';
		$product_out .= '<input type="hidden" id="item_'.$item->id.'_qtyTotal" value="'.$item->qtyTotal.'" />';
		$product_out .= '<input type="hidden" id="item_'.$item->id.'_'.$item->type.'_cur" value="'.$item->qty.'" />';
		
	}
				 
	$product_out .= ' <a rel="'.$item->type.'" alt="'.$item->id.'" name="remove-item_'.$item->id.'" class="remove-cart" href="javascript:void(null)"><img src="images/delete.jpg" /></a></span></div>';
			
    $summary['point'] += ($item->point*$item->qty + $item->pointx*$item->qty);
    $summary['cash']  += ($item->cash*$item->qty);
}
	    
?>
<script type="text/javascript" src="<?php echo JURI::base(); ?>js/dialog/jquery-ui-1.8.20.custom.min.js"></script>
<script src="<?php echo JURI::base(); ?>js/spin/jquery-spin.js"></script>
<script src="<?php echo JURI::base(); ?>js/jquery.cookie.js"></script>
<script src="<?php echo JURI::base(); ?>js/json_encode.js"></script>
<script src="<?php echo JURI::base(); ?>js/json_decode.js"></script>
<script src="<?php echo JURI::base(); ?>js/number_format.js"></script>
<script type="text/javascript">
	
	var scItems = [];
    if(jQuery.cookie("<?php echo md5($session_vipcard_id); ?>") != ""){
        var data_dec = decodeCookies(jQuery.cookie("<?php echo md5($session_vipcard_id); ?>"));
        scItems = json_decode(data_dec);
    }
    var currentUserPoint = "<?php echo $this->userPoint; ?>";    
    var totalPointSubtract = currentUserPoint;

    jQuery(function(){
        totalPointAndCash();
        
		jQuery.spin.imageBasePath = '<?php echo JURI::base(); ?>js/spin/images/spin2/';
        jQuery('.spin2').spin({
            max: 100,
            min: 1
        });
		
        jQuery('.spin2').change(function(){
			
            var objName = jQuery(this).attr("id");
            var item = {
                id:     0,
                qty:    0,
                pcode:  0,
                type:   1,
                img:    '',
                point:  0,
                pointx: 0,
                cash:   0,
                name:   '',
                ptotal: 1  
            };
            
            params = objName.split("_");
            if(params[2] == '2')
                objName = 'item_'+params[1]+'_2';
            else
                 objName = 'item_'+params[1];
            item.id = params[1];

			
			var inputName = jQuery("input[name="+objName+"_type]:checked").attr("id");
            item.type = jQuery("#"+inputName).val();
	
			if(jQuery("input[name="+objName+"_type]:checked").length == 0){
                return false;
            }

            else {
                var qty = jQuery("input[name="+inputName+"_qty]").val();
                //console.log("input[name="+inputName+"_qty");
                var productPoint = 0;
                if(item.type == 1) {
                    item.point = jQuery("#"+inputName+"_point").val();  
                    item.cash = 0;
                    item.pointx = 0;
                    productPoint = (parseInt(qty)*parseInt(item.point));
                }
                else {
                    item.point = 0;
                    item.pointx = jQuery("#"+inputName+"_pointx").val();
                    item.cash = jQuery("#"+inputName+"_cash").val();  
                    productPoint = (parseInt(qty)*parseInt(item.pointx));  
                }
				if(qty <= 0){
                    jQuery("input[name="+inputName+"_qty]").focus();
                    return false;
                }
                else {
                    var subtractPoint = 0;
                    var totalPoint = 0;
					var cashItem   = 0;
                    var totalPointSubtract = 0;
                    
                    if(scItems.length > 0){
                        for(var i=0; i<scItems.length; i++){
							
							for(var i=0; i<scItems.length; i++){
                            if(item.id == scItems[i].id){
                                totalPoint = parseInt(totalPoint) + (qty * parseInt(scItems[i].type == 1 ? scItems[i].point : scItems[i].pointx));
                                //console.log(qty);
                            }else{
                                totalPoint = parseInt(totalPoint) + parseInt(scItems[i].point)*parseInt(scItems[i].qty) + parseInt(scItems[i].pointx)*parseInt(scItems[i].qty);
                            }
                        }
                        }
                    }

            		totalPointSubtract = parseInt(currentUserPoint) - parseInt(totalPoint);
                    var subtractPoint = totalPointSubtract;

                    //console.log(totalPointSubtract);
                    if(subtractPoint > 0){

                        item.qty = qty;
                        item.img = jQuery("#"+objName+"_img").attr("src");
                        item.pcode = jQuery("#"+objName+"_code").html();
                        item.name = objName;
                        
                        var update = 0;
                        var ptotal = 0;
                        
                         if(scItems != undefined && scItems.length > 0){
                            for(var i=0; i<scItems.length; i++){
                                if(scItems[i].id == item.id) {
                                    if(scItems[i].type != item.type) {
                                       update++;
                                    }else{
                                        scItems[i] = item;
                                        update = 0;
                                        break;
                                    }
                                }
                                else{
                                    update++;
                                }
                            }
                            
                            if(update > 0) {
                                scItems.push(item);
                                if(item.type == 1) {
                                    productPoint = (parseInt(item.qty)*parseInt(item.point));
                                }
                                else {
                                    productPoint = (parseInt(item.qty)*parseInt(item.pointx));
                                }                                
                            }
                        }
                        else {
                            scItems.push(item);
                        }
                        
                    }
                    else{
						$('#item_'+item.id).val(parseInt(qty)-1);
						return false;
                    }
                }
            }   
            
            for(var i=0; i<scItems.length; i++){
                if(scItems[i].id == item.id) {
                    ptotal = ptotal + parseInt(scItems[i].qty);
                }
            }
            
            item.ptotal = ptotal;
            /*** Process Data ***/
            jQuery.ajax({
				async: false,
                type: "post",
                url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&layout=addtocart&view=redemptions'); ?>",
                data: "params="+json_encode(item),
                success: function(json){
				
                    var result = eval(json);
					//console.log("Result: "+json_encode(result));
                    if (result.success == true){
					
                        totalPointAndCash();
                    }
                    else
                    {
                    	if(result.refresh == true) page_refresh = true;
						if(scItems != null && scItems.length > 0){
                            for(var i=0; i<scItems.length; i++){
                                if(scItems[i].id == item.id) {
                                    if(scItems[i].type == item.type){
                                        item.qty =  parseInt(scItems[i].qty)-1;
                                        jQuery("#"+item.name).val(item.qty);
                                        if(item.qty <= 0){
                                            scItems.splice(i,1);
                                        }
                                    }
                                }
                            }
                            

							if(result.html != '')
                        		alert(result.html);
                        }
                    }
                }
            }); 
            
			var data_enc = encodeCookies(scItems);
            jQuery.cookie("<?php echo md5($session_vipcard_id); ?>", json_encode(data_enc), { expires: 1, path: '/' });   
            
            if(page_refresh == true){
            	location.reload(true);
            }
            
            return true;
        });
        

        jQuery(".remove-cart").each(function(){
            jQuery(this).click(function(){
                if(scItems != null && scItems.length > 0){
                    removeId = jQuery(this).attr("alt");
					itemType = jQuery(this).attr("rel");
					
					for(var i=0; i<scItems.length; i++){
					
                        if( (removeId == scItems[i].id) && (itemType == scItems[i].type) ){
                            scItems.splice(i,1);
                            jQuery(jQuery(".item_"+removeId+"_"+itemType+"")).fadeOut();

                        }
                    }
                    
                    var data_enc = encodeCookies(scItems);
                    jQuery.cookie("<?php echo md5($session_vipcard_id); ?>", json_encode(data_enc), { expires: 1, path: '/' });                    
                    totalPointAndCash();         
                }
                
                if(scItems.length == 0){
                	$('#checkoutqua').hide();
                	location.reload(true);
                }

                return false;
            });    
        });
    });
    
    function encodeCookies(obj){
		var data ;
    	jQuery.ajax({
    		async: false,
            type: "post",
            url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&task=encryptcart'); ?>",
            data: "params="+json_encode(obj),
            success: function(json){ 
                var result = eval(json);
                
                if (result.success == true)
                {
                	data =  result.data;
                }
                else
                {
                	//console.log('security hole');
                }
            }
        });
        
        return data;
    }
    
    function decodeCookies(obj){
    	var data ;
    	jQuery.ajax({
    		async: false,
            type: "post",
            url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&task=decryptcart'); ?>",
            data: "params="+(obj),
            success: function(json){ 
                var result = eval(json);
                
                if (result.success == true)
                {
                	data =  result.data;
                }
                else
                {
                	//console.log('can not decrypt');
                }
            }
        });
        return data;
    }
    
    function totalPointAndCash(){
        var totalPoint = 0;
        var totalCash = 0;
        //console.log(scItems);
        if(scItems != null && scItems.length > 0){
            for(var i=0; i<scItems.length; i++){
                totalPoint = parseInt(totalPoint) + parseInt(scItems[i].point)*parseInt(scItems[i].qty) + parseInt(scItems[i].pointx)*parseInt(scItems[i].qty);
                totalCash = parseInt(totalCash) + parseInt(scItems[i].cash)*parseInt(scItems[i].qty); 
            }
            totalPointSubtract = parseInt(currentUserPoint) - parseInt(totalPoint);
            
            $('.your_point').html(number_format(currentUserPoint,0,',',','));
			$('.summary_point').html(number_format(totalPoint,0,',',','));
			$('.rest_point').html(number_format(totalPointSubtract,0,',',','));
			$('.total_cash').html(number_format(totalCash,0,',',','));

            jQuery("#redeem-now-link").show(); 
        }else{
        	var your_point = number_format(currentUserPoint, 0,'.',',');
        	var rest_point = your_point;
        	var totalCash = 0;
			var summary_point = 0;
			
			$('.your_point').html(number_format(your_point,0,',',','));
			$('.summary_point').html(number_format(summary_point,0,',',','));
			$('.rest_point').html(number_format(rest_point,0,',',','));
			$('.total_cash').html(number_format(totalCash,0,',',','));

            jQuery("#redeem-now-link").hide();
        }
    }
    
</script>
<div class="row">
	<div class="twelve columns all_reward_header">
		<?php echo $page_heading; ?>
	</div>
</div>

<div id="checkout">
	<div class="product">
		<form action="<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&layout=shoppingcart&view=redemptions&Itemid=112') ?>" method="post" name="adminForm" id="adminForm" >
			<div class="productleft">
	            	<div class="demucmain"><?php echo JText::_('WRD_PROMOTION_INFO_DELIVER'); ?></div>
	                <div class="content">
	                	<p><?php echo JText::_('WRD_PROMOTION_CHOOSE_ONE_PLACE'); ?></p>
	                    <fieldset>
	                    	<legend><?php echo JText::_('WRD_PROMOTION_DELIVER_PLACE'); ?></legend>
                   	
	                        <div class="groupmap">
	                            <span class="mapitem">
	                                <input type="radio" name="pick_up_at" value="111" checked="checked">
	                                    <?php echo JText::_('WRD_PROMOTION_AMIGO'); ?><br />
	                                    <?php echo JText::_('WRD_PROMOTION_AMIGO_ADDR'); ?>
	                                    <img src="images/logo_amigo.png" />
	                        	</span><br>
	                        	<span class="mapitem">
	                                <input type="radio" name="pick_up_at" value="131">
	                                    <?php echo JText::_('WRD_PROMOTION_CCNH'); ?><br />
	                                    <?php echo JText::_('WRD_PROMOTION_CCNH_ADDR'); ?>
	                                    <img src="images/logo_ccnh.png" />
	                        	</span><br>
	                        	<span class="mapitem">
	                                <input type="radio" name="pick_up_at" value="121">
	                                    <?php echo JText::_('WRD_PROMOTION_DUCBAO'); ?><br />
	                                    <?php echo JText::_('WRD_PROMOTION_DUCBAO_ADDR'); ?>
	                                    <img src="images/logo_ducbao.png" />
	                        	</span>
	                        	 <span class="mapitem">
	                                <input type="radio" name="pick_up_at" value="181">
	                                    <?php echo JText::_('WRD_PROMOTION_KISSHO'); ?><br />
	                                    <?php echo JText::_('WRD_PROMOTION_KISSHO_ADDR'); ?>
	                                    <img src="images/logo_kissho.png" />
	                        	</span><br>
	                        	<span class="mapitem">
	                                <input type="radio" name="pick_up_at" value="221">
	                                    <?php echo JText::_('WRD_PROMOTION_CCAD'); ?><br />
	                                    <?php echo JText::_('WRD_PROMOTION_CCAD_ADDR'); ?>
	                                    <img src="images/logo_ccad.png" />
	                        	</span><br>
	                            <span class="mapitem">
	                                <input type="radio" name="pick_up_at" value="211">
	                                    <?php echo JText::_('WRD_PROMOTION_NGANDINH'); ?><br />
	                                    <?php echo JText::_('WRD_PROMOTION_NGANDINH_ADDR'); ?>
	                                    <img src="images/logo_ngandinh.png" />
	                        	</span><br>

	                        	<span class="mapitem">
	                                <input type="radio" name="pick_up_at" value="191">
	                                    <?php echo JText::_('WRD_PROMOTION_TOTT'); ?><br />
	                                    <?php echo JText::_('WRD_PROMOTION_TOTT_ADDR'); ?>
	                                    <img src="images/logo_tott.png" />
	                        	</span>
	                        	<span class="mapitem">
	                                <input type="radio" name="pick_up_at" value="22">
	                                    <?php echo JText::_('WRD_PROMOTION_SPA'); ?><br />
	                                    <?php echo JText::_('WRD_PROMOTION_SPA_ADDR'); ?>
	                                    <img src="images/logo_spa.png" />
	                        	</span>
	                        </div>
	                    </fieldset>
	                </div>
	            </div>
            	<div class="productright">
            		<div class="demucmain"><?php echo JText::_('WRD_PROMOTION_CONFIRM') ?></div>
            		<div class="content">
            			<p>
                    		
							<?php echo JText::_('WRD_PROMOTION_YOUR_POINT') ?><span style="float: right;margin-right: 132px;" class="your_point"><?php echo number_format($this->userPoint, 0,'.',',') ?></span><br>
							<?php echo JText::_('WRD_PROMOTION_SPENDING_POINT') ?><span style="float: right;margin-right: 132px;" class="summary_point"><?php echo number_format($summary['point'], 0,'.',',') ?></span><br>
                        	<?php echo JText::_('WRD_PROMOTION_REST_POINT') ?><span style="float: right;margin-right: 132px;" class="rest_point"><?php echo number_format($summary['point'], 0,'.',',') ?></span>
                        	
							<span><?php echo JText::_('WRD_PROMOTION_TOTAL_CASH') ?> <strong><span class="total_cash"> <?php echo number_format($summary['cash'], 0,'.',',') ?> </span></strong></span>
                    	</p>
                    	<div class="productxn">
	                    	<div class="demuc">
	                        	<span class="column01"><?php echo JText::_('WRD_PROMOTION_PRODUCT') ?></span>
	                            <span class="column02"><?php echo JText::_('WRD_PROMOTION_QUANTITY') ?></span>
	                            <span class="column03"><?php echo JText::_('WRD_PROMOTION_METHOD') ?></span>
	                        </div>
	                        <div class="chitietsp">
	                        	<?php echo $product_out; ?>
	                        </div>
	                        
	                        <div class="buttonxacnhan">
                        		<a href="<?php echo JRoute::_('index.php?option=com_promotions&view=redemptions&Itemid=175'); ?>" id="continue">
                        			<?php echo JText::_('WRD_PROMOTION_CONTINUE_SHOPPING'); ?>
                        		</a>
                            	<input type="submit" value="<?php echo JText::_('WRD_PROMOTION_EXCHANGE_GIFT'); ?>" name="submit" id="checkoutqua">
                        	</div>
                        </div>
					</div>
				</div>
			<?php echo JHTML::_( 'form.token' ); ?>
		</form>
	</div>
</div>
<?php else: ?>
<?php

	$page_heading = JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_CONFIRM');
	$title = JText::_('WMCVIP_TITLE_PREFIX').$page_heading.JText::_('WMCVIP_TITLE_SUFIX');
	$document = &JFactory::getDocument();
	$document->setTitle($title) ;
	 	 
?>
<div class="row">
	<div class="twelve columns all_reward_header">
		<?php echo $page_heading; ?>
	</div>
</div>
<div class="row">
    <div class="twelve columns">
        <div id="checkoutssuccess">
        	<div class="left">
            	<img src="images/imgsuccess.jpg" />
            </div>
            <div class="right">
            	<p><?php echo JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_BODY_DEAR'); ?></p>
                <p>
                	<?php echo JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_BODY_THANKS'); ?><br />
                	<strong class="id"><?php echo $this->redemption_code; ?></strong><br />
                    <?php echo JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_BODY_CONFIRM'); ?><br />
                    <?php echo JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_BODY_KINDLY'); ?><br />
                    <?php echo JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_BODY_SINCERELY'); ?><br />
                    <?php echo JText::_('WRD_PROMOTION_PRODUCT_CHECKOUT_BODY_VIPTEAM'); ?>
                </p>
            </div>
        </div>
    </div>
 </div>
<script type="text/javascript">
	jQuery.cookie("<?php echo md5($session_vipcard_id); ?>", '', { expires: 1, path: '/' });   
</script>
<?php 
endif; ?>